import { addPanelTag, destroyLayer } from '@/service';
import { useSceneStore } from '@/store/scene';
import { debounce, round } from 'lodash';

export const useDrag = () => {
  const sceneStore = useSceneStore();
  const resizing = ref<boolean>(false);
  let calcPosition = null as any;

  const onDivPointerDown = (e: PointerEvent) => {
    resizing.value = true;
    (e.target as any).setPointerCapture(e.pointerId);
    const targetDom = document.querySelectorAll(
      `.gis-container-web-div.${sceneStore.selLayer.layerName}`
    );
    if (!targetDom.length) return;
    const targetDomPosition = targetDom[0].getBoundingClientRect();
    calcPosition = {
      x: e.clientX - targetDomPosition.left,
      y: e.clientY - targetDomPosition.top,
    };
  };
  const onDivPointerMove = debounce(
    (e: PointerEvent) => {
      const { cimInstance } = window;
      if (resizing.value && sceneStore.divEditLayerName) {
        (e.target as any).style.cursor = 'move';

        // 计算实际坐标点
        const actualDomPosition = {
          x: e.clientX - calcPosition.x,
          y: e.clientY - calcPosition.y,
        };
        console.log('实际移动坐标----', actualDomPosition);

        const targetPosition = cimInstance.api.screenToDegreesHeight({
          x: round(actualDomPosition.x),
          y: round(actualDomPosition.y),
        });
        // 删除dom
        destroyLayer(sceneStore.selLayer);
        addPanelTag({
          longitude: targetPosition[0],
          latitude: targetPosition[1],
          height: targetPosition[2],
          ...sceneStore.selLayer,
        });
        sceneStore.selLayer.attr.position = targetPosition;
      }
    },
    20,
    {
      leading: true,
      trailing: false,
    }
  );
  const onDivPointerUp = (e: PointerEvent) => {
    resizing.value = false;
    (e.target as any).style.cursor = 'pointer';
    (e.target as any).releasePointerCapture(e.pointerId);
    calcPosition = null;
  };
  return {
    onDivPointerDown,
    onDivPointerMove,
    onDivPointerUp,
  };
};
